<!DOCTYPE html>
<html lang="en">
<title>优惠券列表</title>
<#import "/layout/layout.html" as body/>
<@body.page>

<!--<div class="row wrapper border-bottom white-bg page-heading">
    <div class="col-lg-10">
        <h2>优惠券管理</h2>
        <ol class="breadcrumb">
            <li><a href="../store_list.html">优惠券管理</a></li>
            <li class="active"><strong>优惠券列表</strong></li>
        </ol>
    </div>
</div>-->
<div class="wrapper wrapper-content animated fadeInRight">
    <div class="row">
        <div class="col-lg-12">
            <div class="ibox float-e-margins">
                <div class="ibox-title">
                    <h5 class="pull-left">优惠券列表</h5>
                    <a href="${baseUrl}system/coupon/to_add_step1" class="btn btn-sm btn-primary pull-right">新增优惠券</a>
                </div>
                <div class="ibox-content">

                    <div class="table-responsive">
                        <form class="form-inline" role="form">
                            <div class="form-group margin-left">
                                <label for="id">券ID：</label>
                                <input class="form-control" id="id" type="text" placeholder="请输入券ID"/>
                            </div>
                            <div class="form-group margin-left">
                                <label>限制类型：</label>
                                <select class="form-control" id="isLimitCourse">
                                    <option value="">全部</option>
                                    <option value="0">会员资格</option>
                                    <option value="1">团课</option>
                                    <option value="2">私教</option>
                                    <option value="3">训练营</option>
                                    <option value="4">自健</option>
                                </select>
                            </div>
                            <div class="form-group margin-left">
                                <label>状态：</label>
                                <select class="form-control" id="couponStatus">
                                    <option value="">全部</option>
                                    <option value="1">系统录入</option>
                                    <option value="2">已上架</option>
                                    <option value="3">已下架</option>
                                    <option value="4">已删除</option>
                                </select>
                            </div>
                            <button type="button" id="search" class="btn btn-outline btn-primary" style="margin-top: 5px">确认</button>
                        </form>
                        <hr style="width: 100%">
                        <table class="table table-hover table-center">
                            <thead>
                            <tr>
                                <th>批次ID</th>
                                <th>券类型</th>
                                <th>券名</th>
                                <th>兑换代码</th>
                                <th>面值</th>
                                <th>兑换期限</th>
                                <th>使用期限</th>
                                <th>仅限</th>
                                <!--<th>限制门店</th>-->
                                <th>限量</th>
                                <th>已领取张数</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody id="couponList">
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="ibox-content overflow">
                    <h4 class="pull-left">合计：<span id="couponCount">0</span>张优惠券</h4>
                    <div id="copot-page" class="pull-right"></div>
                </div>
            </div>
        </div>
    </div>
  
</div>
<div style="display: none;" id="testDiv">
	 
</div>
<script src="${baseUrl}js/channel/jquery.qrcode.min.js"></script>
<script>

    //搜索
    $("#search").click(function () {
        coursePage(1)
    });

    $(document).ready(function () {

        Date.prototype.pattern = function (fmt) {
            var o = {
                "M+": this.getMonth() + 1, //月份
                "d+": this.getDate(), //日
                "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时
                "H+": this.getHours(), //小时
                "m+": this.getMinutes(), //分
                "s+": this.getSeconds(), //秒
                "q+": Math.floor((this.getMonth() + 3) / 3), //季度
                "S": this.getMilliseconds() //毫秒
            };
            var week = {
                "0": "/u65e5",
                "1": "/u4e00",
                "2": "/u4e8c",
                "3": "/u4e09",
                "4": "/u56db",
                "5": "/u4e94",
                "6": "/u516d"
            };
            if (/(y+)/.test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            }
            if (/(E+)/.test(fmt)) {
                fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : "") + week[this.getDay() + ""]);
            }
            for (var k in o) {
                if (new RegExp("(" + k + ")").test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                }
            }
            var str = fmt.lastIndexOf("N");
            if (str != -1) {
                return "";
            }

            return fmt;
        }

        coursePage(1);
    });


        //导出excel
        ExampleFile("门店excel");


        function coursePage(currentIndex) {
            var param = {
                "pageIndex": currentIndex,
                "pageSize": 10,
                "id": $("#id").val(),
                "isLimitCourse": $("#isLimitCourse").val(),
                "couponStatus": $("#couponStatus").val()
            };

            $.post("${baseUrl}system/coupon/coupon_list", param, function (result) {

                //分页
                new Page({
                    parent: $("#copot-page"),
                    nowPage: currentIndex,
                    pageSize: 10,
                    totalCount:  result.couponCount,
                    setting: {
                        defaultPage: 5,//默认显示可点击分页的个数
                        firstPageText: "首页",
                        prevPageText: "上一页",
                        nextPageText: "下一页",
                        lastPageText: "尾页"
                    },
                    callback: function (nowPage, totalPage) {
                        coursePage(nowPage);
                    }
                });

                $("#couponCount").text(result.couponCount);

                var html = "";
                var couponCode = null;
                var changeBeginDate = null;
                var changeEndDate = null;
                var useBeginDate = null;
                var useEndDate = null;
                var couponType = null;
                var cashMoney = null;
                var isLimitCourse = null;
                var maxCount = null;
                var couponStatus = null;

                $.each(result.couponList, function (i, data) {
                	console.log(data)
                    if(data.getMode){
                        if(data.getMode ==2){
                            couponCode = "系统生成";
                        } else{
                            couponCode = data.couponCode;
                        }
                    }
                    if(data.couponType){
                        if(data.couponType == '1'){
                            couponType = "现金券";
                            cashMoney = "¥"+data.cashMoney;
                        }
                        if(data.couponType == '2'){
                            couponType = "折扣券";
                        }
                        if(data.couponType == '3'){
                            couponType = "檬会员";
                        }
                        if(data.couponType == '4'){
                            couponType = "课程体验券";
                        }
                        if(data.couponType == '5'){
                            couponType = "团课包月卡体验劵";
                        }
                    }
                    // 这里只有在现金券的时候才显示金额 其余的显示''
                    if(data.couponType == '1'){
                        cashMoney = "¥"+data.cashMoney;
                    } else {
                        cashMoney = "/";
                    } 
                    if (data.changeBeginDate) {
                        changeBeginDate = new Date(data.changeBeginDate).pattern("yyyy-MM-dd");
                    } else {
                        if(data.changeMode == 1){
                            changeBeginDate = "无限制";
                        }else {
                            changeBeginDate = "无数据";
                        }
                    }
                    if (data.changeEndDate) {
                        changeEndDate = new Date(data.changeEndDate).pattern("yyyy-MM-dd");
                    } else {
                        changeEndDate = "";
                    }
                    if (data.useBeginDate) {
                        useBeginDate = new Date(data.useBeginDate).pattern("yyyy-MM-dd");
                    } else {
                        if(data.useMode ==1){
                            useBeginDate = "领取日起"+ data.dayNum +"天";
                        } else{
                            useBeginDate = "无数据";
                        }
                    }
                    if (data.useEndDate) {
                        useEndDate = new Date(data.useEndDate).pattern("yyyy-MM-dd");
                    } else {
                        useEndDate = "";
                    }
                    if(data.isLimitCourse && data.isLimitCourse == "1"){
                        isLimitCourse = "无限制";
                    } else{
                        debugger
                        isLimitCourse = "";
                        if(data.limitTeamCourse == 1){
                            isLimitCourse +="团课";
                        }
                        if(data.limitSecretCourse == 1){
                            if(isLimitCourse.length >0){
                                isLimitCourse +="|"
                            }
                            isLimitCourse +="私教";
                        }
                        if(data.limitCampCourse == 1){
                            if(isLimitCourse.length >0){
                                isLimitCourse +="|"
                            }
                            isLimitCourse +="训练营";
                        }
                        if(data.limitSelfCourse == 1){
                            if(isLimitCourse.length >0){
                                isLimitCourse +="|"
                            }
                            isLimitCourse +="自助健身";
                        }
                    }
                    if(data.couponType == '3'){
                        isLimitCourse = "檬会员资格";
                    }
                    if(data.maxCount >=0){
                        if( data.maxCount == 0){
                            maxCount = "无限";
                        }else{
                            maxCount = data.maxCount;
                        }
                    } else {
                        maxCount = "无数据";
                    }
                    if(data.couponStatus){
                        if(data.couponStatus == 1){
                            couponStatus = "系统录入";
                        }
                        if(data.couponStatus == 2){
                            couponStatus = "已上线";
                        }
                        if(data.couponStatus == 3){
                            couponStatus = "已下线";
                        }
                        if(data.couponStatus == 4){
                            couponStatus = "已删除";
                        }
                    }
                    html += "<tr><td>" + data.id + "</td>";
                    html += "<td>" + couponType + "</td>";
                    html += "<td>" + data.couponName + "</td>";
                    html += "<td>" + couponCode + "</td>";
                    html += "<td>" + cashMoney + "</td>";
                    html += "<td>" + changeBeginDate +"<br>"+ changeEndDate + "</td>";
                    html += "<td>" + useBeginDate +"<br>"+ useEndDate + "</td>";
                    html += "<td>" + isLimitCourse + "</td>";
                    html += "<td>" + maxCount + "</td>";
                    html += "<td>" + data.getedCount + "</td>";
                    html += "<td>" + couponStatus + "</td>";
                    html += "<td>";

                    html += "<button type='button' onclick='detailCoupon(" + data.id + ")' class='btn btn-default'><i class='fa fa-pencil'></i> 查看</button>";

                    if(data.couponStatus && data.couponStatus != 3) {
                        html += "<button type='button' onclick='editCoupon(" + data.id + ")' class='btn btn-default'><i class='fa fa-pencil'></i> 编辑</button>";
                    }
                    if(data.couponStatus && data.couponStatus == 2){
                        html += "<button type='button' onclick='offlineCoupon(" + data.id + ")' class='btn btn-default'><i class='fa fa-arrow-circle-down'></i> 下架</button>";
                    }
                    if(data.getMode && data.getMode ==2 && maxCount !="无限"){
                        html += "<button type='button' id=download"+data.id+" onclick='downloadCoupon(" + data.id + ")' class='btn btn-default'><i class='fa fa-arrow-circle-down'></i> 下载</button>";
                    }
                    
                    if(couponCode == '系统生成'){
                        html += "<button type='button' id=download"+data.id+" onclick='downloadImg(" + data.id + ",\"" + data.couponName + "\")' class='btn btn-default'><i class='fa fa-arrow-circle-down'></i>生成二维码</button>";
                    }
                    html += "</td>";
                    html += "</tr>";
                });
                $("#couponList").html(html);

            });


        }
    /**
     * 查看领取记录
     *
     * @param id
     */
    function detailCoupon(id) {
    window.location = "${baseUrl}system/coupon/to_get_list?couponId="+id;
    }

    /**
     * 编辑优惠券
     *
     * @param id
     */
    function editCoupon(id) {
        window.location = "${baseUrl}system/coupon/to_add_step1?id="+id;
    }

    /**
     * 下架优惠券
     *
     * @param id
     */
    function offlineCoupon(id) {
        //下架优惠券
        swal({
            title: "确定要下架吗?",
            type: "warning",
            showCancelButton: true,
            cancelButtonText: "容我三思！",
            confirmButtonText: "下架!"
        }).then(function () {
            $.post("${baseUrl}system/coupon/offlineCoupon/"+id,function (result) {
                if(result && result == "success"){

                    swal("下架成功!", "页面即将重新加载,请稍后...", "success");
                    window.setTimeout(function () {
                        window.location.reload(true);
                    }, 1000);
                } else {
                    swal("错误!", result, "error");
                }
            });
        });

    }

    /**
     * 下载优惠券
     *
     * @param id
     */
    function downloadCoupon(id) {
    	/**
    	$("#download"+id).css("display", "none");
    	debugger;
    	 $.post("${baseUrl}system/coupon/coupon_detail_down?id="+id,function (res) {
    		 res = eval("(" +res +")");
    		 debugger
    		if(res && res.data.result == "success"){
    			swal("成功!",'文件下载成功！', "success");
    			$("#download"+id).css("display", "");
    			window.location ="${baseUrl}system/coupon/download_file?fileName="+res.data.fileName;
    			
    		} else{
    			 swal("错误!", res.data.msg, "error");
    			 $("#download"+id).css("display", "");
    		}
    	 });
    	 */
    	 swal.queue([{
    		  title: '优惠券下载',
    		  confirmButtonText: '确定',
    		  text:
    		    '请点击确定后开始下载优惠券信息',
    		  showLoaderOnConfirm: true,
              allowOutsideClick: false,
    		  preConfirm: function () {
    		    return new Promise(function (resolve) {
    		      $.get('${baseUrl}system/coupon/coupon_detail_down?id='+id)
    		        .done(function (res) {
    		        	 res = eval("(" +res +")");
    		    		 debugger
    		    		if(res && res.data.result == "success"){
    		    			//swal("成功!",'文件下载成功！', "success");
    		    			$("#download"+id).css("display", "");
    		    			window.location ="${baseUrl}system/coupon/download_file?fileName="+res.data.fileName;
    		    			resolve();
    		    		} else{
    		    			 resolve();
    		    			 swal("错误!", res.data.msg, "error");
    		    			 $("#download"+id).css("display", "");
    		    		}
    		        })
    		    })
    		  }
    		}]);
    }
    
    function downloadImg(id,fileName){
    	
    	 new Promise(function (resolve) {
  		      $.get('${baseUrl}system/coupon/coupon_detail_down?id='+id)
  		        .done(function (res) {
  		        	$.get("${baseUrl}system/coupon/short_url?conponId="+id, function (result) {
  		      		data = eval('(' +result+')');
  		              var shortUrl = data.data
  		              
  		              fileName= fileName+".jpg";
  		          	$("#testDiv").empty();
  		          	var html = '<div id="qrcode"></div><a id="download" download="qrcode.jpg"></a><button id="save">save</button>';
  		          	$("#testDiv").append(html);
  		          	console.log(shortUrl)
  		          	jQuery('#qrcode').qrcode({render:"canvas", text:shortUrl, width: 500,height: 500, background:"#ffffff",foreground: "#000000" });
  		          	var canvas = $('#qrcode').find("canvas").get(0);  
  		              var urlnew = canvas.toDataURL(shortUrl);  
  		              $("#download").attr('download',fileName).click(); 
  		              $("#download").attr('href', "").click(); 
  		              $("#download").attr('href', urlnew).get(0).click(); 
  		              
  		              return false;    
  		          	});
  		        })
  		    })
    }
</script>
</@body.page>
</html>